import OSS from 'ali-oss'
import { Message } from '@arco-design/web-vue'
import { getStsToken } from '@/api/task'

const getToken: any = () => {
  return new Promise((resolve, reject) => {
    getStsToken()
      .then((res: any) => {
        const { data } = res
        const { accessKeyId, accessKeySecret, securityToken, expiration } = data
        const client = new OSS({
          region: 'oss-cn-shenzhen',
          accessKeyId,
          accessKeySecret,
          stsToken: securityToken,
          // 填写Bucket名称。
          bucket: 'static-erp',
        })
        resolve(client)
      })
      .catch((e) => {
        Message.error('获取直传KEY失败')
        reject(e)
      })
  })
}

export const OSSUpload = (file: File, basePathUrl?: string) => {
  let names = file.name.split('.')
  let type = names[names.length - 1]
  let day = new Date()
  let year = day.getFullYear()
  let month = day.getMonth()
  var randomNumber = Math.floor(1000000000000000 + Math.random() * 9000000000000000)
  return new Promise((resolve, reject) => {
    getToken().then((client: any) => {
      let gloablePath = `/task/${year}/${month}/${names[0]}_${randomNumber}.${type}`
      let taskPath = ''
      if (basePathUrl) taskPath = `${basePathUrl}/${names[0]}_${randomNumber}.${type}`
      client
        .put(basePathUrl ? taskPath : gloablePath, file)
        .then((res: any) => {
          let result = res
          result.url = decodeURIComponent(result.url)
          result.old_name = file.name
          resolve(result)
        })
        .catch((e: any) => {
          Message.error('文件上传失败')
          reject(e)
        })
    })
  })
}

export const mulUpload = (fileList: any) => {
  let promiseList: any = []
  for (let index = 0; index < fileList.length; index++) {
    ;((i) => {
      promiseList.push(OSSUpload(fileList[i]))
    })(index)
  }
  return Promise.all(promiseList)
  // return new Promise((resolve, reject) => {
  //   Promise.all(promiseList)
  //     .then((res) => {
  //       resolve(res)
  //     })
  //     .catch((e) => {
  //       reject(e)
  //     })
  // })
}
